﻿
using MS_Enitity;
using MS_Enitity.EAP;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using TextFile;
using xktComm.Common;
using xktComm.DataConvert;
using xktNodeSettings.Node.Device;
using xktNodeSettings.Node.Variable;

namespace MS_UI
{
    public static class CommMethods
    {


        #region 定位全局变量


        //板架距离
        public static short RackDistance = 0;

        //串口通讯配置
        public static List<string> CommInfo = new List<string>();

        //主窗体对象
        public static FrmMain objFrmMain;   

        //三菱PLC设备集合
        public static List<NodeMelsec> MelsecList = new List<NodeMelsec>();

        //报警变量信息集合
        public static List<MelsecVariable> Alarm_Variable_List = new List<MelsecVariable>();

        //变量-数值 键值对
        public static Dictionary<string, object> CurrentMelsecValue = new Dictionary<string, object>();

        //字典的键是变量名称，值是对应的变量对象
        public static Dictionary<string, MelsecVariable> CurrentMelsecVarList = new Dictionary<string, MelsecVariable>();


        // 批次信息队列
        public static ConcurrentQueue<Task_info> concurrentQueue = new ConcurrentQueue<Task_info>();


        public static List<Task_info> jobDataDownloadList = new List<Task_info>();

        public static List<Task_info> RcvEAP_task_List = new List<Task_info>(); 
            

             
        public static List<JobData> jobdataList = new List<JobData>();

        //工位1当前批次信息
        public static Task_info Current_task_info1 = new Task_info();

        //工位2当前批次信息
        public static Task_info Current_task_info2 = new Task_info();

        //工位3当前批次信息
        public static Task_info Current_task_info3 = new Task_info();

        public static List<PanelID> panelList = new List<PanelID>(); 

        public static bool  EAPIsConnected; 

        //激光触发信号
        public  static  short LaserTriggerSignal;  
        
        //激光上次触发信号
        public static  short OldLaserTrigger; 

        //按钮触发信号
        public static bool LaserBtnTrigger;


        public static string port1Position;

        public static string port2Position;

        public static string port3Position;

        public static string port1TaskCode;
        public static string port2TaskCode;
        public static string port3TaskCode;

        public static string port1ReqCode;
        public static string port2ReqCode;
        public static string port3ReqCode;

        #endregion


        #region 读取通讯配置文件
        /// <summary>
        /// 读取PLC通讯配置文件
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static List<string> GetFactor(string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Open);
            StreamReader sr = new StreamReader(fs, Encoding.Default);
            List<string> list = new List<string>();
            while (true)
            {
                string str = sr.ReadLine();
                if (str == null) break;
                list.Add(str.Trim());
            }
            sr.Close();
            fs.Close();
            return list;
        }
        #endregion

        #region DGV双缓冲
        /// <summary>
        /// dataGirdView刷新
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="setting"></param>
        public static void DoubleBuffered(this DataGridView dgv, bool setting)
        {
            Type dgvType = dgv.GetType();
            PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
            BindingFlags.Instance | BindingFlags.NonPublic);
            pi.SetValue(dgv, setting, null);


        }
        #endregion

        #region 设置文本框数值，不写入PLC
        public static  void InputTxtValue(object sender,string MinValue,string MaxValue,string PointNO)
        {
            string CrruentValue = ((TextBox)sender).Text;
            Point p = ((TextBox)sender).Location;
            Frmkeyboard ObjFrmkeyboard = new Frmkeyboard(CrruentValue, MinValue, MaxValue, PointNO);
          //  ObjFrmkeyboard.Location = new Point(p.X + 1, p.Y + 35);
            ObjFrmkeyboard.Location = new Point(430, 100);
            DialogResult Res = ObjFrmkeyboard.ShowDialog();

            if (Res == DialogResult.OK)
            {
                ((TextBox)sender).Text = ObjFrmkeyboard.OutValue;
            }
        }
        #endregion

        #region 设置文本框数值，写入PLC
        public static void SetLblValue(object sender)
        {

            if (sender is Label lb)
            {
                if (lb.Tag != null && lb.Tag.ToString().Length > 0)
                {
                    if (CommMethods.CurrentMelsecVarList.ContainsKey(lb.Tag.ToString()))
                    {
                        Frmkeyboard ObjFrmkeyboard = new Frmkeyboard(lb.Tag.ToString());
                        ObjFrmkeyboard.Location = new Point(430, 100);
                        DialogResult Res = ObjFrmkeyboard.ShowDialog();
                    }
                }
            }
        }
        #endregion

        #region 设置TextBox数值，写入PLC
        public static void SetTextValue(object sender)
        {

            if (sender is TextBox text)
            {
                if (text.Tag != null && text.Tag.ToString().Length > 0)
                {
                    if (CommMethods.CurrentMelsecVarList.ContainsKey(text.Tag.ToString()))
                    {
                        Frmkeyboard ObjFrmkeyboard = new Frmkeyboard(text.Tag.ToString());
                        ObjFrmkeyboard.Location = new Point(430, 100);
                        DialogResult Res = ObjFrmkeyboard.ShowDialog();
                    }
                }
            }
        }
        #endregion




        #region 设置按钮数值，写入PLC
        public static void SetBtnValue(object sender, string SetValue)
        {
            short value = 0;
            if (sender is Button btn)
            {
                if (btn.Tag != null && btn.Tag.ToString().Length > 0)
                {
                    CommMethods.CommonMelsecWrite(CommMethods.CurrentMelsecVarList[btn.Tag.ToString()], SetValue);
                    string VarAddress = CommMethods.CurrentMelsecVarList[btn.Tag.ToString()].VarAddress;
                    string ShortVarAddress = VarAddress.Substring(0, VarAddress.IndexOf("."));
                    bool flag = CommMethods.MelsecList[0].melsec.ReadShort(ShortVarAddress, ref value);
                    bool BitValue = BitLib.GetBitFromShort(value, Convert.ToInt16(VarAddress.Substring(VarAddress.IndexOf(".") + 1),16), true);

                    if (btn.Tag.ToString().Contains("-2"))
                    {
                        btn.BackColor = (BitValue == false) ? Color.FromArgb(224, 224, 224) : Color.Red;
                        btn.Text = (BitValue == false) ? "启用" : "关闭";
                    }
                    else
                    {
                        btn.BackColor = (BitValue == false) ? Color.FromArgb(224, 224, 224) : Color.Lime;
                    }
                }
            }
        }
        #endregion

        #region 数值写入PLC地址变量操作
        public static bool CommonMelsecWrite(MelsecVariable variable, string value)
        {
            bool Result = false;

            try
            {
                switch (variable.VarType)
                {
                    case DataType.Bool:
                        Result = MelsecList[0].melsec.Write(variable.VarAddress, value == "1" || value.ToLower() == "true", true);
                        break;
                    case DataType.Byte:
                        Result = MelsecList[0].melsec.Write(variable.VarAddress, Convert.ToByte(value));
                        break;
                    case DataType.Short:
                        Result = MelsecList[0].melsec.Write(variable.VarAddress, Convert.ToInt16(value));
                        break;
                    case DataType.UShort:
                        Result = MelsecList[0].melsec.Write(variable.VarAddress, Convert.ToUInt16(value));
                        break;
                    case DataType.Int:
                        Result = MelsecList[0].melsec.Write(variable.VarAddress, Convert.ToInt32(value));
                        break;
                    case DataType.UInt:
                        Result = MelsecList[0].melsec.Write(variable.VarAddress, Convert.ToUInt32(value));
                        break;
                    case DataType.Float:
                        Result = MelsecList[0].melsec.Write(variable.VarAddress, Convert.ToSingle(value));
                        break;
                    case DataType.Double:
                        Result = MelsecList[0].melsec.Write(variable.VarAddress, Convert.ToDouble(value));
                        break;
                    case DataType.Long:
                        Result = MelsecList[0].melsec.Write(variable.VarAddress, Convert.ToInt64(value));
                        break;
                    case DataType.ULong:
                        Result = MelsecList[0].melsec.Write(variable.VarAddress, Convert.ToUInt64(value));
                        break;
                    case DataType.String:
                        //通信库内部会自动通过识别地址  DB1.DBS1.10   DB1.DBS1|10         
                        Result = MelsecList[0].melsec.Write(variable.VarAddress.Substring(0, variable.VarAddress.IndexOf(".")), value);
                        break;
                    default:
                        break;
                }

                return Result;
            }
            catch (Exception)
            {
                return false;
            }

        }

        #endregion

        public static  bool[]  GetbitfromInt(int a)
        { 
            byte[] bytelit = ByteArrayLib.GetByteArrayFromInt(a, DataFormat.DCBA);

            bool[] boollit = BitLib.GetBitArrayFromByteArray(bytelit, false);

            return boollit;
        }



    }
}
